import React from 'react';
import { observer, inject } from 'mobx-react';
import { Route, withRouter, Switch } from 'react-router-dom';
import { RouteLayout } from 'weaver-mobile-page'
import { Schedule, Icon } from 'weaver-mobile';
import moment from 'moment';
import ItemCard from '../../public/ItemCard';
import MeetingUtil from '../../util/meetingUtil';
import Report from '../../components/report';

@inject('meetingSearchStore')
@inject('calendarStore')
@inject('viewMeetingStore')
@withRouter
@observer
export default class MeetingCalendar extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      visible: false,
      nowTab:0,
      canlendarHeight: 0
    };
    this.refSchedule = React.createRef();
    this.refCalendar = React.createRef();
  }

  componentDidMount() {
    const { setState } = this.props.calendarStore;
    //判断sessionStorage中是否存在值,如果存在,那么就取其中的值,不存在那么就取now Date()
    let localDate = ''
    let localMeetingType = '0'
    let selectUser = ''
    if(sessionStorage&&sessionStorage.meetingSelectdate){
      localDate = sessionStorage.meetingSelectdate
    }else{
      localDate = moment(this.state.date).format("YYYY-MM-DD")
    }
    if(sessionStorage&&sessionStorage.meetingSelectUserId){
      selectUser = sessionStorage.meetingSelectUserId
    }
    //根据sessionStorage中是否存在meetingNowTab,判断跳转tab页面以及meetingType
    //因为meetingType是根据tab.key来决定的,所以两者是同一个值
    if(sessionStorage&&sessionStorage.meetingNowTab){
      this.setState({ nowTab: parseInt(sessionStorage.meetingNowTab,10) })
      localMeetingType = sessionStorage.meetingNowTab
    }
    setState({selectdate:localDate,meetingType:localMeetingType})
    this.getDetail({meetingType:parseInt(localMeetingType,10),selectUser:selectUser})
  }

  getDetail(params){
    const { selectdate,setState } = this.props.calendarStore;
    setState(...params)
    this.getCalendarList({selectdate:selectdate,...params});
    this.getCalendarInfo({selectdate:selectdate,...params});
  }

  componentDidUpdate() {
    if(this.refSchedule.current && this.refCalendar.current && this.refCalendar.current.clientHeight != this.state.canlendarHeight) {
      this.setState({ canlendarHeight: this.refCalendar.current.clientHeight });
    }
  }

  componentWillReceiveProps (nextProps) {
    if(this.props.selectUser !== nextProps.selectUser || nextProps.selectUser===''){
      const selectUser = sessionStorage.meetingSelectUserId?sessionStorage.meetingSelectUserId:''
      const localMeetingType = sessionStorage.meetingNowTab
      this.getDetail({meetingType:localMeetingType,selectUser:selectUser})
    }
  }

  componentWillUnmount () {
    
  }

  getCalendarInfo(params){
    const { getCalendarInfo,meetingType } = this.props.calendarStore;
    getCalendarInfo({ismobile:1,viewType:'3',isCalendar:'1',meetingType:meetingType,...params});
  }

  getCalendarList(params){
    const { getCalendarInfo,meetingType } = this.props.calendarStore;
    getCalendarInfo({ismobile:1,viewType:'1',isCalendar:'0',meetingType:meetingType,...params});
  }

  viewDetail = (params) => {
    const { history } = this.props;
    sessionStorage.setItem('type','view')
    history.push({pathname:`/calendar/detail`,query:{meetingid:params,type:'view'}});
  }

  setRequestParams = (v)=>{
    const { onlyFlowCreate, requestFieldIds,begintime,endtime , setState } = this.props.viewMeetingStore;
    if(onlyFlowCreate === 1){
      const meetingDate = v;
      let urlParamsTemp = [];
      requestFieldIds&&Object.keys(requestFieldIds).map((item)=>{
        if(item === 'begindate'){
          requestFieldIds.begindate&&requestFieldIds.begindate.map(item1=>{
            meetingDate&&urlParamsTemp.push(`&${item1}=${meetingDate}`)
          })
        }
        if(item === 'begintime'){
          requestFieldIds.begintime&&requestFieldIds.begintime.map(item1=>{
            begintime&&urlParamsTemp.push(`&${item1}=${begintime}`)
          })
        }
        if(item === 'enddate'){
          requestFieldIds.enddate&&requestFieldIds.enddate.map(item1=>{
            meetingDate&&urlParamsTemp.push(`&${item1}=${meetingDate}`)
          })
        }
        if(item === 'endtime'){
          requestFieldIds.endtime&&requestFieldIds.endtime.map(item1=>{
            endtime&&urlParamsTemp.push(`&${item1}=${endtime}`)
          })
        }
        
        if(item === 'beginDateTime'){
          requestFieldIds.beginDateTime&&requestFieldIds.beginDateTime.map(item1=>{
            meetingDate&&begintime&&urlParamsTemp.push(`&${item1}=${meetingDate} ${begintime}`)
          })
        }
        if(item === 'endDateTime'){
          requestFieldIds.endDateTime&&requestFieldIds.endDateTime.map(item1=>{
            meetingDate&&endtime&&urlParamsTemp.push(`&${item1}=${meetingDate} ${endtime}`)
          })
        }
      })
      setState({addRequestUrlParams:urlParamsTemp.join('')})
    }
  }

  getLoading = () => {
    return (
      <div className='loaidng-icon' key='loading' style={{textAlign: 'center'}}>
        <Icon type='loading' size='lg'/>
      </div>
    );
  }

  render() {
    const { calendarStore } = this.props
    const { calendarInfo,calendarList,setState,selectdate,weekStartDay,isInit } = calendarStore;
    //获取日历高度
    const calendarHeight = document.getElementById('myCalendar')&&document.getElementById('myCalendar').offsetHeight;
    const innerHeight = this.getHeight();
    //样式中top:10,排除<xx天后 星期x>的高度,所以这边需要加上这个10来计算calendarlist高度
    const buttonHeight = this.getBottomHeight() + 10 ;
    return (
      <div>
        <div id="myCalendar" ref={this.refCalendar} canlendarHeight={this.state.canlendarHeight}>
        {
          !isInit?
          this.getLoading()
          :
          <Schedule
            ref={this.refSchedule}
            defaultDate={selectdate===''?sessionStorage.getItem('meetingSelectdate')?new Date(sessionStorage.getItem('meetingSelectdate')):new Date():new Date(selectdate)}
            dateExtra={calendarInfo}
            onMonthChange={(month, range, title) =>
              new Promise((resolve) => {
                setState({startDate:month[0],endDate:month[1]})
                this.getCalendarInfo({selectdate:month[0],selectUser:sessionStorage.meetingSelectUserId})
              })
            }
            onSelect={v => {this.setRequestParams(v);setState({selectdate:v}); this.getCalendarList({selectdate:v,selectUser:sessionStorage.meetingSelectUserId}); sessionStorage.meetingSelectdate=v;sessionStorage.meetingRoomPlanDate=v}}
            weekStart={weekStartDay}
          />
        }
          
        </div>
        {/* <div id="calendarList" className={'calendarListDiv'} style={{height:innerHeight-calendarHeight}}> */}
        <div id="calendarList" className={'calendarListDiv'} style={{height:innerHeight-calendarHeight-buttonHeight}}>
          <ItemCard datas={calendarList} onRowClick={this.viewDetail} nodataHeight={innerHeight-calendarHeight-5}/>
        </div>
        <Switch>
          <Route
            key="report"
            path="/calendar/*/report"
            render={()=>(
              <RouteLayout>
              <div key="reportnDiv" className="wm-route-layout wm-demo-route-layout-page" style={{height: 'calc(100% - 51px)'}}>
                <Report />
              </div>
              </RouteLayout>
            )}
          />
        </Switch>
      </div>
    )
  }

  getHeight = () => {
    return document.body.clientHeight - MeetingUtil.getTabHeight();
  }

  getBottomHeight = () => {
    return MeetingUtil.getBaseHeight() * 65;
  }

}